# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
# secGear is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
# http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.

import argparse
import logging
import sys
from pathlib import Path

from secharden.rule_metadata import RuleManager
from secharden.utils import DirectoryPathVerifier, HOME_DIR

TITLE = "安全 OS 配置工具"


def generate_doc(root: Path, overwrite: bool):
    rules = RuleManager(root)

    output = root.joinpath("README.md")
    if output.exists():
        if overwrite:
            logging.warning("force to generate doc, deleting existing doc files")
            output.unlink()
        else:
            raise FileExistsError(f"File {output} already exists")
    else:
        output.touch()

    output_stream = output.open(mode='wt', encoding='utf-8')
    output_stream.write(f"# {TITLE}\n\n")

    for category_id in rules.categories:
        output_stream.write(rules.get_category_desc(category_id).doc)
        for rule in rules.get_rules_by_category(category_id):
            logging.info(f"Generating doc for rule: {rule}")
            output_stream.write(rules.get_rule_metadata(rule).doc)
    output_stream.write("\n")
    output_stream.write("> Generated By docgen tool.\n\n")
    output_stream.close()


def main(argv=None):
    args = argparse.ArgumentParser(prog="docgen")
    args.add_argument("-r", "--rules", action=DirectoryPathVerifier,
                      help="rule script directory", default=HOME_DIR.joinpath('tools'))
    args.add_argument('-f', '--force', action='store_true',
                      help="force to generate doc, deleting existing doc files")
    version_file = HOME_DIR.joinpath("VERSION")
    args.add_argument('-v', '--version', action='version', version=version_file.read_text('utf-8').strip())
    args.add_argument("-d", "--debug", action='store_true', help="debug mode")
    args = args.parse_args(argv)

    logging_level = logging.INFO
    if args.debug:
        logging_level = logging.DEBUG
    logging.basicConfig(level=logging_level, format='%(asctime)s [%(levelname)8s] %(message)s')

    try:
        generate_doc(Path(args.rules), overwrite=args.force)
    except Exception as e:
        logging.error(f"Error generating documentation: {e}")
        logging.exception(e)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
